package com.xp.agent.classTransformer;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.Modifier;

public class ServletChanger {

	public static byte[] modifyClass() throws Exception {
		ClassPool pool = ClassPool.getDefault();
		CtClass ctClass = pool.get("javax.servlet.http.HttpServlet");
		CtMethod[] declaredMethod = ctClass.getDeclaredMethods();
		for (CtMethod method : declaredMethod) {
			String oldName =method.getName();
			if (oldName.equals("service")) {
				CtMethod copy = CtNewMethod.copy(method, ctClass, null);
				copy.setName(oldName);
				copy.setModifiers(method.getModifiers());
				String newName = oldName+"xp";
				method.setName(newName);
				method.setModifiers(Modifier.PRIVATE);
				ctClass.addMethod(copy);
				StringBuilder sb =new StringBuilder();
				sb.append("{");
				sb.append("System.out.println(\"hello\");");
				String returnType = method.getReturnType().getName();
				if(!"void".equals(returnType)){
					sb.append(returnType+" obj =");
				}
				sb.append(newName+"($$);");
				sb.append("}");
				copy.setBody(sb.toString());
			}
		}
		ctClass.writeFile("C:/fff");
		ctClass.defrost();

		return null;
	}

}
